package com.test.mywebapp.client;

import com.test.mywebapp.shared.FieldVerifier;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Grid;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class MyWebApp implements EntryPoint {

	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";
	final Button sendButton 		= new Button("Send");
	final Button resetButton 		= new Button("Reset");
	final TextBox nameField 		= new TextBox();
	final Label errorLabel 			= new Label();
	final DialogBox dialogBox 		= new DialogBox();
	final Button closeButton 		= new Button("Close");
	final Label textToServerLabel 	= new Label();
	final HTML serverResponseLabel 	= new HTML();
	VerticalPanel dialogVPanel 		= new VerticalPanel();

	Board board 	= new Board();
	Grid boardGrid 	= new Grid(3,3);
	
	/**
	 * Create a remote service proxy to talk to the server-side Greeting service.
	 */
	private final GreetingServiceAsync greetingService = GWT
			.create(GreetingService.class);

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
	
		// Add text to the name field.
		nameField.setText("GWT User");
		
		// Put some values in the grid cells.
	    for (int i = 0, row = 0; row < 3; ++row) {
	      for (int col = 0; col < 3; ++col){
	    	  boardGrid.setWidget(row, col, board.getImage(i));
	    	  i++;
	      }
	    }

		// We can add style names to widgets
		sendButton.addStyleName("sendButton");

		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
		RootPanel.get("nameFieldContainer").add(nameField);
		RootPanel.get("sendButtonContainer").add(sendButton);
		RootPanel.get("resetButtonContainer").add(resetButton);
		RootPanel.get("errorLabelContainer").add(errorLabel);
		RootPanel.get("boardContainer").add(boardGrid);

		// Focus the cursor on the name field when the application loads.
		nameField.setFocus(true);
		nameField.selectAll();

		// Create the pop up dialog box. 
		this.createPopUpDialog();
		
		// Create the event handlers.
		this.createEventHandlers();

		// Reset the board.
		this.resetPlayArea();
	}
	
	/**
	 * This method resets the game.
	 */
	private void resetPlayArea()
	{
		board.reset();
	}
	
	/**
	 * Creates the pop up dialog.
	 */
	private void createPopUpDialog() {
		
		// Create the pop up dialog box
		dialogBox.setText("Remote Procedure Call");
		dialogBox.setAnimationEnabled(true);
		
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");
		
		// Create the Panel
		dialogVPanel.addStyleName("dialogVPanel");
		dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
		dialogVPanel.add(textToServerLabel);
		dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
		dialogVPanel.add(serverResponseLabel);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);

		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
				sendButton.setEnabled(true);
				sendButton.setFocus(true);
			}
		});
	}
	
	/**
	 * Creates the event handlers.
	 */
	private void createEventHandlers() {
		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		sendButton.addClickHandler(handler);
		nameField.addKeyUpHandler(handler);
		ResetHandler resetHandle = new ResetHandler(this.board);
		resetButton.addClickHandler(resetHandle);
	}

	/**
	 * Create a handler for the sendButton and nameField
	 */
	private class MyHandler implements ClickHandler, KeyUpHandler {
		/**
		 * Fired when the user clicks on the sendButton.
		 */
		public void onClick(ClickEvent event) {
			sendNameToServer();
		}

		/**
		 * Fired when the user types in the nameField.
		 */
		public void onKeyUp(KeyUpEvent event) {
			if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
				sendNameToServer();
			}
		}

		/**
		 * Send the name from the nameField to the server and wait for a response.
		 */
		private void sendNameToServer() {
			// First, we validate the input.
			errorLabel.setText("");
			String textToServer = nameField.getText();
			if (!FieldVerifier.isValidName(textToServer)) {
				errorLabel.setText("Please enter at least four characters");
				return;
			}

			// Then, we send the input to the server.
			sendButton.setEnabled(false);
			textToServerLabel.setText(textToServer);
			serverResponseLabel.setText("");
			greetingService.greetServer(textToServer,
					new AsyncCallback<String>() {
						public void onFailure(Throwable caught) {
							// Show the RPC error message to the user
							dialogBox
									.setText("Remote Procedure Call - Failure");
							serverResponseLabel
									.addStyleName("serverResponseLabelError");
							serverResponseLabel.setHTML(SERVER_ERROR);
							dialogBox.center();
							closeButton.setFocus(true);
						}

						public void onSuccess(String result) {
							dialogBox.setText("Remote Procedure Call");
							serverResponseLabel
									.removeStyleName("serverResponseLabelError");
							serverResponseLabel.setHTML(result);
							dialogBox.center();
							closeButton.setFocus(true);
						}
					});
		}
	}
	
	private class ResetHandler implements ClickHandler{

		private Board board = null;
		
		ResetHandler(Board aBoard){
			this.board = aBoard;
		}
		
		@Override
		public void onClick(ClickEvent event) {
			this.board.reset();
		}
		
	}
}
